<?php

/**
 * MODEL CREATOR 2012
 * @package ModelCreator
 * @subpackage GenerateFile  
 * @copyright 2012/11/01 - MODEL CREATOR
 * @version GenerateFile.php 1.0  
 * @since File that contains class used for create php files
 */
/**
 * Class GenerateFile user to create all files
 * @package ModelCreator
 * @subpackage GenerateFile  
 * @author Renato Laranjo <renatolaranjo@gmail.com>
 * @release: $package_version$
 * @since Class since 2012   
 */
include_once 'Database/Connection.php';

class ModelCreator_GenerateFile {

    /**
     * Atribute that contains a path
     * @var string 
     */
    private $_path;

    /**
     *  Atribute that contains all objects for the connection
     * @var object 
     */
    private $_allObjects;

    /**
     *  Atribute that contains language 
     * @var string 
     */
    private $_language;

    /**
     * Atribute that contains the project name
     * @var string
     */
    private $_project;

    /**
     * Atribute that contains data user for nomenclature
     * @var array
     */
    private $_nomenclature;

    /**
     * Atribute that contains all additional information
     * @var array
     */
    private $_plus;

    /**
     * Atribute used to return all files created 
     * @var array 
     */
    private $_file;

    /**
     * Constructor method - receives all post data and call methods that creates php files
     * @param type $arrPost
     * @return void
     */
    public function __construct($arrPost) {
        $this->_path = $arrPost['path'];
        $this->_language = $arrPost['language'];
        $this->_project = $arrPost['connection']['project'];
        $this->_nomenclature = $arrPost['nomenclature'];
        $this->_plus = $arrPost['plus'];
        unset($arrPost['language']);
        $this->_allObjects = new ModelCreator_Database_Connection($arrPost[connection], $arrPost[object]);
        $array = $this->createFile();
        echo json_encode($array);
    }

    /**
     * Function that creates files and set its names
     * @return array
     */
    private function createFile() {
        $pref_file = $this->_nomenclature['pref_file'];
        $suf_file = $this->_nomenclature['suf_file'];
        //Get all objects
        $tables = $this->_allObjects->objConn->_allTables;
        //Verify files
        $this->verifyProject();
        foreach ($tables as $value) {
            $table = $value;
            $tableName = substr($value, 2);
            $arrayTableName = explode("_", $tableName);
            if (count($arrayTableName) > 1) {
                $i = 0;
                foreach ($arrayTableName as $value2) {
                    $arrayTableNameForm[$i++] = ucfirst(strtolower($value2));
                }
                $tableNameFormated = implode("", $arrayTableNameForm);
                $fileName = $pref_file . $tableNameFormated . $suf_file . ".php";
            } else {
                $tableNameFormated = ucfirst(strtolower($tableName));
                $fileName = $pref_file . $tableNameFormated . $suf_file . ".php";
            }

            $handle = fopen("../models/" . $this->_project . DIRECTORY_SEPARATOR . $fileName, 'w') or die("can't open file");
            $script = "<?php" . PHP_EOL;
            $script .= $this->writeFile($tableNameFormated, $table);
            $script .= "}";

            fwrite($handle, $script);
            fclose($handle);
        }
        $files = glob("../models/" . $this->_project . DIRECTORY_SEPARATOR . "*");
        $xhtml = $this->returnXHTML($files);
        $return['files'] = $this->_file;
        $return['xhtml'] = $xhtml;
        return $return;
    }

    /**
     * Clean files and verify with it is a new project 
     */
    private function verifyProject() {
        if (!file_exists("../models/" . $this->_project)) {
            mkdir("../models/" . $this->_project);
        } else {
            $files = glob("../models/" . $this->_project . DIRECTORY_SEPARATOR . "*");
            foreach ($files as $file) {
                unlink($file);
            }
        }
    }

    /**
     * Function that write all information into a file
     * @param string $tableNameFormated
     * @param string $tableName
     * @return string
     */
    private function writeFile($tableNameFormated, $tableName) {
        $pref_class = $this->_nomenclature['pref_class'];
        $suf_class = $this->_nomenclature['suf_class'];
        $pref_seq = $this->_nomenclature['pref_seq'];
        $suf_seq = empty($this->_nomenclature['suf_seq']) ? "_SEQ" : $this->_nomenclature['suf_seq'];

        $handle = fopen(getcwd() . "/ModelCreator/Language/ClassFile/{$this->_language}/ClassModel.txt", "r");
        $script = fread($handle, 4096);
        $organization = (!empty($this->_plus['organization'])) ? $this->_plus['organization'] : 'MODEL CREATOR';
        $script = str_replace('ORGANIZATION', $organization, $script);
        //Select language to set date
        $date = ($this->_language == 'en') ? date('Y-m-d') : date('d/m/Y');
        $script = str_replace('YEAR_FILE ', $date . " - ", $script);
        $script = str_replace('FILENAME', $tableNameFormated . ".php 1.0", $script);
        $script = str_replace('TABLENAME_CLASS', $tableNameFormated, $script);
        $author = (empty($this->_plus['author'])) ? 'model.creator' : $this->_plus['author'];
        $script = str_replace('AUTHOR', $author, $script);
        $package = (!empty($this->_plus['package'])) ? $this->_plus['package'] : 'Application';
        $script = str_replace('PACKAGE', $package, $script);
        $subpackage = (!empty($this->_plus['subpackage'])) ? $this->_plus['subpackage'] : 'Models';
        $script = str_replace('SUBPACK', $subpackage, $script);
        if (!empty($this->_plus['extend'])) {
            $script = str_replace('Zend_Db_Table', $this->_plus['extend'], $script);
        }
        $script = str_replace('YEAR_CLASS', date('Y'), $script);
        $script = str_replace('NAMECLASS', $pref_class . $tableNameFormated . $suf_class, $script);
        $script = str_replace('SCHEMA', "'" . $this->_allObjects->_schema . "'", $script);
        $script = str_replace('TABLENAME', "'" . $tableName . "'", $script);

        //Get all primary keys for earch table
        $arrPrimaryKey = $this->_allObjects->objConn->_allPrimaryKeys[$tableName];
        if ($this->_nomenclature['opt_seq_name'] == 'table_name') {
            $script = str_replace('SEQUENCE', "'" . $pref_seq . $tableName . $suf_seq . "'", $script);
        } elseif ($this->_nomenclature['opt_seq_name'] == 'key' && count($arrPrimaryKey) == 1) {
            $script = str_replace('SEQUENCE', "'" . $pref_seq . $arrPrimaryKey[0] . $suf_seq . "'", $script);
        } elseif ($this->_nomenclature['opt_seq_name'] == 'key' && count($arrPrimaryKey) == 0) {
            $script = str_replace('SEQUENCE', "'" . "''", $script);
        } else {
            $script = str_replace('SEQUENCE', "'" . "''", $script);
        }

        //Get primary key
        if (count($arrPrimaryKey) == 1) {
            $script = str_replace('PRIMARY', "'" . strtoupper($arrPrimaryKey[0]) . "'", $script);
        } elseif (count($arrPrimaryKey) == 0) {
            $script = str_replace('PRIMARY', "''", $script);
        } else {
            $arrPrimaryKeyFormated = "array(";
            foreach ($arrPrimaryKey as $value) {
                if (end($arrPrimaryKey) == $value) {
                    $arrPrimaryKeyFormated .= "'" . strtoupper($value) . "')";
                } else {
                    $arrPrimaryKeyFormated .= "'" . strtoupper($value) . "',";
                }
            }
            $script = str_replace('PRIMARY', $arrPrimaryKeyFormated, $script);
        }
        $arrColumns = $this->_allObjects->objConn->_allColumns[$tableName];
        $language = new ModelCreator_Language_Selector();
        //Set table name as constant
        $script .= "    /**" . PHP_EOL;
        $script .= "     * {$arrLanguage['table']} {$$tableName}" . PHP_EOL;
        $script .= "     * @var string" . PHP_EOL;
        $script .= "     */ " . PHP_EOL;
        $script .= "    const _NAME" . " = '" . $tableName . "';" . PHP_EOL;
        $script .= PHP_EOL;

        //Get All Columns

        $arrLanguage = $language->detect();
        foreach ($arrColumns as $value) {
            $script .= "    /**" . PHP_EOL;
            $script .= "     * {$arrLanguage['column_name']} {$value['COLUMN']}" . PHP_EOL;
            $script .= "     * @var {$value['DATATYPE']}" . PHP_EOL;
            $script .= "     */ " . PHP_EOL;
            $script .= "    const _" . strtoupper($value['COLUMN']) . " = '" . $value['COLUMN'] . "';" . PHP_EOL;
            $script .= PHP_EOL;
        }
        fclose($handle);

        return $script;
    }

    /**
     * Function that return a formatted HTML with all filenames and informations
     * @param array $files
     * @return string
     */
    private function returnXHTML($files) {
        $lang = new ModelCreator_Language_Selector();
        $arrLanguage = $lang->detect();
        $filesize = 0;
        foreach ($files as $file) {
            $filesize = filesize($file) + $filesize;
        }
        $i = 1;
        $xhtml = "<div id='resultEffect'>";
        $xhtml .= "<h3>{$arrLanguage['result']}</h3>";
        $xhtml .= "<span id='spanLabel'>{$arrLanguage['count']}</span> <span id='spanResult'>" . count($files) . "</span> | ";
        $xhtml .= "<span id='spanLabel'>{$arrLanguage['size']}</span> <span id='spanResult'>" . $filesize . " bytes </span> | ";
        $xhtml .= "<span id='spanResultLink'><img id='id_zip' src='image/zip.png' width='30px' height='30px' />&nbsp;{$arrLanguage['compress']}</span>";
        $xhtml .= "<hr />";
        $xhtml .= "<table id='idResultTable' width='100%'>";
        foreach ($files as $file) {
            $fileName = str_replace("../models/" . $this->_project . DIRECTORY_SEPARATOR, "", $file);
            $this->_file[$fileName] = $fileName;
            $xhtml .= "<tr id='idtdResult' title='{$arrLanguage['click_view']}' onclick=showFileContent('" . $fileName . "'); class='tdtable'>";
            $xhtml .= "<td width='30px'>";
            $xhtml .= "<img src='image/file-icon.png' width='25px' height='25px' /></td>";
            $xhtml .= "<td valign='middle'>" . $fileName;
            $xhtml .= "</td>";
            $xhtml .= "</tr>";
        }

        $xhtml .= "</table>";
        $xhtml .= "</div>";
        return $xhtml;
    }

}
